<template>
  <div>
    <el-row :gutter="20" style="height: 100%">
      <el-col :span="5" style="height: 100%">
        <el-card style="height: 100%">
          <el-button-group circle style="margin-bottom: 5px">
            <el-button type="primary" icon="el-icon-plus" style="padding:8px" @click="openGroupAdd"></el-button>
            <el-button type="primary" icon="el-icon-edit" style="padding:8px" @click="openGroupEdit"></el-button>
            <el-button type="primary" icon="el-icon-delete" style="padding:8px" @click="deleteGroup"></el-button>
          </el-button-group>
          <el-input style="margin-bottom: 5px" placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
          <el-tree v-loading="treeLoading" class="filter-tree tree-scroll" :data="groupTreeData" :props="defaultProps" node-key="nodeId" :default-expanded-keys="[-1]" @node-click="handleNodeClick" highlight-current :expand-on-click-node="false" :filter-node-method="filterNode" ref="groupTree">
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="19" style="padding-left: 0">
        <el-card>
          <el-form inline>
            <el-form-item label="名称:" class="mgb-0">
              <el-input v-model="fname"></el-input>
            </el-form-item>
            <el-form-item label="编码:" class="mgb-0">
              <el-input v-model="fnumber"></el-input>
            </el-form-item>
            <el-form-item label="规格型号:" class="mgb-0">
              <el-input v-model="fmodel"></el-input>
            </el-form-item>
            <el-form-item label="助记码:" class="mgb-0">
              <el-input v-model="fmnemoniccode"></el-input>
            </el-form-item>
            <el-form-item class="mgb-0">
              <el-button type="primary" icon="el-icon-search" @click="searchData"></el-button>
              <el-button type="success" icon="el-icon-refresh" @click="clearData"></el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card style="margin-top: 10px">
          <div style="margin-bottom: 10px">
<!--            <el-button type="primary" @click="openAdd">新增</el-button>-->
<!--            <el-button type="primary" @click="batchEnable(0)">批量启用</el-button>
            <el-button type="danger" @click="batchEnable(1)">批量禁用</el-button>
            <el-button type="danger" @click="batchRemove">删除</el-button>-->
<!--            <el-button type="success" @click="batchPrint">标签打印</el-button>-->
          </div>
          <el-table border :data="dataList" v-loading="tableLoading" ref="iTable1" @row-click="handleRowClick">
            <el-table-column align="center" type="selection" width="55"></el-table-column>
            <el-table-column label="编码" prop="fnumber" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="名称" prop="fname" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="简称" prop="fsimplename" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="规格" prop="fmodel" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="助记码" prop="fmnemoniccode" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="属性" prop="ftype" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="启用批号" prop="fuselot" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-tag v-if="scope.row.fuselot ==0" type="danger">否</el-tag>
                <el-tag v-if="scope.row.fuselot ==1" type="success">是</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="免检" prop="fisavoidcheck" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-tag v-if="scope.row.fisavoidcheck ==0" type="danger">否</el-tag>
                <el-tag v-if="scope.row.fisavoidcheck ==1" type="success">是</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" show-overflow-tooltip width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.fstatus =='USED'" type="success">启用</el-tag>
                <el-tag v-if="scope.row.fstatus =='UNUSED'" type="danger">禁用</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="80">
              <template slot-scope="scope">
                <el-button type="text" @click.stop="openDetail(scope.row.fid)">详情</el-button>
                <el-button type="text" v-if="scope.row.fstatus =='UNUSED'" @click.stop="openEdit(scope.row.fid)">编辑</el-button>
                <!-- <el-button type="text" style="color: red" v-if="scope.row.fstatus =='USED'" @click="disEnable(scope.row.fid, '禁用')">禁用</el-button>
                <el-button type="text" v-if="scope.row.fstatus =='UNUSED'" @click="disEnable(scope.row.fid, '启用')">启用</el-button>
                <el-button type="text" style="color: red" @click="delete(scope.row.fid)">删除</el-button> -->
              </template>
            </el-table-column>
          </el-table>
          <el-pagination style="float:right; margin: 10px 0;" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page" :page-sizes="[10, 15, 20, 50]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" prev-text="上一页" next-text="下一页" :total="totalRows">
          </el-pagination>
        </el-card>
      </el-col>
    </el-row>
    <!--新增-->
    <material_addEdit v-if="showPages.addEdit" :fid="fid" :status="status" :fgroupid="fgroupId" :isview="isview" @close="closeAddEdit" @notRefresh="notRefresh"></material_addEdit>
    <!--详情-->
    <material_detail v-if="showPages.detail" :fid="fid" @close="closeDetail"></material_detail>


  </div>
</template>

<script>
import Tsyu from "@/api/basedataManager/Tsyu";
import TsGroup from "@/api/basedataManager/TsGroup";
import { flatTurnTree } from '@/utils/DataTypeConvert'
import material_detail from "@/views/basedataManager/components/material_detail";
import material_addEdit from "@/views/basedataManager/components/material_addEdit";
import Sortable from 'sortablejs';
export default {
  name: 'material_manage',
  components: {
    material_addEdit,
    material_detail,
    Sortable,

  },
  data () {
    return {
      filterText: '',
      groupTreeData: [],
      defaultProps: {
        children: 'children',
        label: 'nodeName'
      },
      material:{
        fname: '',
        fnumber: '',
        fgroupId: 0,
        fmnemoniccode: null,
        fmodel: null,
        status: '',
        fid: 0,
      },
      fparentgroupId: 0,
      treeLoading: false,
      tableLoading: false,
      dataList: [],
      pages:{
        page: 1, //当前页面
        pageSize: 10, // 当前页数
        totalRows: 0, // 总条数
      },
      showPages:{
       addEdit:false,
       detail:false,
        groupAddEdit:false,
        groupDetail:false,
      },
      isview: false,
      services: new Tsyu(),
      isShowPrint: false,
      printIds: []
    }
  },
  watch: {
    filterText (val) {
      this.$refs.groupTree.filter(val);
    }
  },
  async created () {
    //this.treeLoading = true
    let http = new TsGroup()
    const groupTreeData = await http.queryGroupTree({})
    console.log(groupTreeData)
    this.groupTreeData = flatTurnTree(groupTreeData.data, 'nodeId', 'nodePid', -2)
    //this.treeLoading = false
    this.getData()
  },
  methods: {
    initGroup() {
      const http=new Tsyu();
      console.log(this._getData())
      this.tableLoading=true
      http.queryListPage().then(res =>{
        this.tableLoading=false;
        this.pages=res.data

      })
    },
    batchPrint () {
      const _selectData = this.$refs.iTable1.selection
      if (_selectData.length == 0) {
        this.$tie.showError('请至少选择一条数据！')
        return
      }
      this.printIds = new Array();
      for (var i = 0; i < _selectData.length; i++) {
        this.printIds[i] = _selectData[i].fid;
      }
      this.isShowPrint = true
    },
    filterNode (value, data) {
      if (!value) return true;
      return data.nodeName.indexOf(value) !== -1;
    },
    handleNodeClick (val) {
      if (val.nodeId === -1) {
        this.fgroupId = 0
      } else {
        this.fgroupId = val.nodeId
      }
      this.page = 1
      this.getData()
    },
    //获取表格数据源
    getData () {
      let http = new Tsyu()
      this.tableLoading = true
      http.queryListPage(this.material).then(res => {
        this.dataList = res.data.rows
        this.page = res.data.page
        this.pageSize = res.data.pageSize
        this.totalRows = res.data.totalRows
        this.tableLoading = false
      })
    },
    // 当前页码修改时
    handleCurrentChange (page) {
      this.page = page
      this.getData()
    },
    // 当前页数修改时
    handleSizeChange (pageSize) {
      this.pageSize = pageSize
      this.getData()
    },
    searchData () {
      this.page = 1
      this.getData()
    },
    clearData () {
      this.fname = null
      this.fnumber = null
      this.fmnemoniccode = null
      this.fmodel = null
    },
    //打开新增弹窗
    openAdd () {
      if (!this.fgroupId) {
        this.$message.error('请选择分类!')
        return
      }
      this.fid = null
      this.isview = false
      this.status = 'add'
      this.isShowMaterialAddEdit = true
    },
    //打开编辑弹窗
    openEdit (id) {
      this.fid = id
      this.isview = false
      this.status = 'update'
      this.isShowMaterialAddEdit = true
    },
    //关闭新增编辑弹窗
    closeAddEdit () {
      this.isShowMaterialAddEdit = false
      this.fid = ''
      this.getData()
    },
    notRefresh () {
      this.isShowMaterialAddEdit = false
      this.fid = ''
    },
    //打开详情弹窗
    openDetail (id) {
      this.fid = id
      this.isview = true
      this.status = 'view'
      this.isShowMaterialAddEdit = true
    },
    //关闭详情弹窗
    closeDetail () {
      this.fid = ''
      this.isShowMaterialAddEdit = false
    },
   /* //禁用或启用
    disEnable (fid, text) {
      const loading = this.$loading({
        lock: true,
        text: `${text}中，请耐心等待.....`,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      let http = new Tsyu()
      let fstatus = text === '禁用' ? 1 : 0
      http.changeStatus({ fid, fstatus }).then(res => {
        this.$message.success(`${text}成功!`)
        loading.close()
        this.getData()
      }).catch(e => {
        loading.close()
      })
    },
    //删除
    delete (id) {
      this.$confirm('此操作将永久删除该物料, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: `删除中，请耐心等待.....`,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        let http = new Tsyu()
        http.delete({ fid }).then(res => {
          this.$message({ type: 'success', message: '删除成功!' })
          loading.close()
          this.getData()
        }).catch(e => {
          loading.close()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },*/
    handleRowClick (row, column, event) {
      this.$refs.iTable1.toggleRowSelection(row)
    },
    //打开新增弹窗
    openGroupAdd () {
      if (!this.fgroupId) {
        this.fgroupId = -1;
      }
      let parentid = this.fgroupId
      this.fparentgroupId = parentid+''
      this.fgroupId = null
      this.$refs.groupTree.setCurrentKey()
      this.isShowGroupAddEdit = true
    },
    //打开编辑弹窗
    openGroupEdit (id) {
      if (!this.fgroupId || this.fgroupId == -1 || this.fgroupId == '-1') {
        this.$message.error('请选择分类!')
        return
      }
      this.isShowGroupAddEdit = true

    },
    //关闭新增编辑弹窗
    closeGroupAddEdit () {
      this.isShowGroupAddEdit = false
      this.fgroupId = null
      this.fparentgroupId = null
      this.refreshAll()
    },
    groupNotRefresh () {
      this.fparentgroupId = null
      this.isShowGroupAddEdit = false
    },
    //删除
    deleteGroup (id) {
      if (!this.fgroupId) {
        this.$message.error('请选择分类!')
        return
      }
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: `删除中，请耐心等待.....`,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        let http = new TsGroup()
        let groupId = this.fgroupId
        http.delete({ fid: groupId }).then(res => {
          this.$tie.showSuccess(res.message)
          loading.close()
          this.refreshAll()
        }).catch(e => {
          loading.close()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      this.refreshAll()
    },
    /*
    batchEnable (status) {
      var fids = this.getSelectIdByTable();
      if (fids.length == 0) {
        this.$message.error('未选中数据!')
      } else {
        const loading = this.$loading({
          lock: true,
          text: `批量操作中，请耐心等待.....`,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.services.batchChangeState({ "fid": fids, "fstatus": status }).then(res => {
          this.$tie.showSuccess(res.message)
          loading.close();
          this.getData();
        }).catch(e => {
          loading.close();
        })
      }
    }, batchRemove () {
      var fids = this.getSelectIdByTable();
      if (fids.length == 0) {
        this.$message.error('未选中数据!')
      } else {
        const loading = this.$loading({
          lock: true,
          text: `批量操作中，请耐心等待.....`,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.services.batchDelete({ "fid": fids }).then(res => {
          this.$tie.showSuccess(res.message)
          loading.close();
          this.getData();
        }).catch(e => {
          loading.close();
        })
      }

    },*/
    getSelectIdByTable () {
      var batchChoose = this.$refs.iTable1.selection;
      var fids = [];
      for (var i = 0; i < batchChoose.length; i++) {
        fids[i] = batchChoose[i].fid;
      }
      return fids;
    },
    async refreshAll () {
      this.treeLoading = true
      let http = new TsGroup();
      this.groupTreeData = [];
      this.groupTreeData = await http.queryGroupTree({});
      this.groupTreeData = flatTurnTree(this.groupTreeData.data, 'nodeId', 'nodePid', -2);
      this.treeLoading = false
      this.getData();
    },
  },
}
</script>

<style scoped lang="scss" >
/deep/.tree-scroll {
  height: 93%;
  overflow: scroll;
}
/deep/ .el-card__body {
  height: 100%;
}
</style>

